package com.woniu.service.impl;

import com.woniu.dao.CourseDao;
import com.woniu.dao.OrderDao;
import com.woniu.dao.UserDao;
import com.woniu.entity.Course;
import com.woniu.entity.Order;
import com.woniu.entity.PageResult;
import com.woniu.entity.User;
import com.woniu.entity.dto.OrderDTO;
import com.woniu.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CourseDao courseDao;

    @Override
    public PageResult<Order> getOrdersByPage(String orderMethod, Integer status, Integer userId,String username,Integer pageNum, Integer pageSize) {
        PageResult<Order> pageable = new PageResult<>();
        pageable.setPageNum(pageNum);
        pageable.setPageSize(pageSize);
        //计算总数
        pageable.setTotal(orderDao.count(orderMethod, status,username,userId));
        // 计算总页数
        pageable.setPages((int) (pageable.getTotal() / pageable.getPageSize() + (pageable.getTotal() % pageable.getPageSize() == 0 ? 0 : 1)));
        // 查询分页数据
        pageable.setList(orderDao.queryAllByLimit(orderMethod, status,userId,username, pageable));
        return pageable;
    }

    //更新备注
    @Override
    public void updateRemark(String orderId, String remark) {
        orderDao.updateRemark(orderId, remark);
    }

    //获取订单详情
    @Override
    public Order getOrderById(String orderId) {
        return orderDao.getOrderById(orderId);
    }

    /**
     * 创建多个订单（属于同一个总订单）
     * @param orders 订单数组
     * @return 总订单编号
     */
    @Transactional
    @Override
    public String createOrders(List<Order> orders) {
        // 生成总订单编号
        String orderNo = generateOrderNo();
        Date now = new Date();

        for (Order order : orders) {
            //生成订单编号
            String orderId = generateOrderNo();
            order.setOrderId(orderId);
            order.setStatus(0);     // 未支付状态
            order.setCreateTime(now);
            order.setUpdateTime(now);

            orderDao.insertOrder(order);
        }

        return orderNo;
    }


//    @Override
//    @Transactional
//    public Order createOrder(OrderDTO orderDTO) {
//        Order order = new Order();
//        // 生成订单编号
//        String orderNo = generateOrderNo();
//        //生成订单id
//        String orderId = orderNo;
//
//        // 设置订单信息
//        order.setOrderId(orderId);
////        order.setCourseId(orderDTO.getCourseId());
////        order.setCourseName(orderDTO.getCourseTitle());
//        order.setPrice(orderDTO.getPrice());
//        order.setOrderMethod(orderDTO.getPaymentMethod());
//        order.setRemark(orderDTO.getRemark());
//        order.setStatus(1); // 0表示未支付
//        order.setCreateTime(new Date());
//        order.setUpdateTime(new Date());
//
//        // 保存订单
//        orderDao.insertOrder(order);
//
//        return order;
//    }

    // 生成订单编号
    private String generateOrderNo() {
        return "ORD" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 4).toUpperCase();
    }

    //支付帮
    @Override
    public List<Map<String, Object>> getPaymentRankings() {
        return orderDao.getPaymentRankings();
    }

    /**
     *
     * @param userId
     * @param courseId
     * @return 查询是否购买
     */
    @Override
    public Integer selectUC(Integer userId, Integer courseId) {
        return orderDao.selectUC(userId, courseId) ;
    }

    /**
     * 查询购买的课程
     * @param userId
     * @param
     * @return
     */
    @Override
    public List<Course> selectOrder(Integer userId) {
        return orderDao.selectOrder(userId);
    }
 @Override
    public List<Course> getCoursesByOrderId(String orderId) {
        return orderDao.getCoursesByOrderId(orderId);
    }

    @Override
    public Map<String, Object> getCourseDetailWithUser(Long courseId) {
        Map<String, Object> result = new HashMap<>();
        Course course = courseDao.getCourseById(courseId);
        if (course != null && course.getTeacherId() != null) {
            User teacher = userDao.getUserById(course.getTeacherId());
            result.put("course", course);
            result.put("teacher", teacher);
        }
        return result;
    }

    @Override
    public void deleteOrder(String orderId) {
        orderDao.deleteOrder(orderId);
    }

    @Override
    public void deleteOrderAndCourse(String orderId) {
        orderDao.deleteOrderAndCourse(orderId);
    }


    // OrderServiceImpl.java 修改收藏逻辑
    @Override
    public void addsc(Integer userId, Integer courseId) {
        // 先检查是否已存在
        if (orderDao.selectUidByCid(userId, courseId) != null) {
            throw new RuntimeException("已收藏该课程");
        }
        orderDao.addsc(userId, courseId);
    }

    @Override
    public Integer selectUidByCid(Integer userId, Integer courseId) {
        return orderDao.selectUidByCid(userId, courseId);
    }

    @Override
    public void delectsc(Integer userId, Integer courseId) {
        if (orderDao.selectUidByCid(userId, courseId) == null) {
            throw new RuntimeException("未收藏该课程");
        }
        orderDao.delectsc(userId, courseId);
    }

}
